#include "qdlgregister.h"
#include "ui_qdlgregister.h"

//add by dimon, 2024-03-17 11:10
#include <QMessageBox>
#include <QHostAddress>
#include "common.h"
#include <QtDebug>

qdlgregister::qdlgregister(QString ip, QString port,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::qdlgregister)
{
    ui->setupUi(this);

    this->ip = ip;
    this->port = port;

    //new申请一个QTcpSocket对象
    tcpSocket = new QTcpSocket(this);
    //关联信号-槽
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(onReadyRead()));

}

qdlgregister::~qdlgregister()
{
    delete ui;
}

//槽 函数
void qdlgregister::onReadyRead(){
    //从QTcpSocket读取数据
    QByteArray block = tcpSocket->readAll();
    //把数据流QDataStream和 byteArray关联起来，数据流为只读QIODevice::ReadOnly
    QDataStream in(&block, QIODevice::ReadOnly);
    quint16 dataGramSize;
    quint8 msgType;

    //数据流QDataStram ‘>>’提取运算符 提取数据到 dataGramSize, msgType, userId
    in >> dataGramSize >> msgType >> userid;

    if(msgType  == MSG_SERVER_REG_FAILED){
        QMessageBox::warning(NULL, tr("提示"), tr("注册失败。"));
        return;
    }
    else if(msgType == MSG_SERVER_REG_SUCCESS){
        QMessageBox::information(NULL, tr("消息"), tr("注册成功."));
        this->close();
    }
}

//add by dimon, 2024-03-17 11:10
//“注册"按钮，发送消息到服务器，使用QTcpSocket套接字
void qdlgregister::on_pushbtnRegister_clicked()
{
    QString name = ui->lineEditUsername->text().trimmed();
    password = ui->lineEditPasswd->text().trimmed();
    QString password2 = ui->lineEditPasswdRep->text().trimmed();


    qDebug() << "dimon chen" << endl;


    if(name.isEmpty()){
        QMessageBox::warning(NULL, tr("提示"), tr("昵称不能为空。"));
        return ;
    }
    else if((password != password2) || password.isEmpty()){
        QMessageBox::warning(NULL, tr("提示"), tr("密码不能为空且两次输入要一致"));
        return;
    }

    //使用 QTcpSocket
    tcpSocket->abort();
    //QTcpSocket 连接到服务器IP和port

    qDebug() << "connect to IP" << ip << " to Port " << port << endl;

    tcpSocket->connectToHost(QHostAddress(ip), (quint16)port.toUInt());
    //发送注册信息
    quint8 msgType = MSG_CLIENT_REG;
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_4);
    out << (quint16)0 << msgType << name << password;
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));
    //把byteArry 数组写入QTcpSocket
    tcpSocket->write(block);
}
